const clickoutsideContext = '@@clickoutsideContext'

export const clickoutside = {
  beforeMount(el, binding) {
    const handler = (event) => {
      if (!el.contains(event.target) && el !== event.target) {
        binding.value(event)
      }
    }
    el[clickoutsideContext] = {
      handler,
      eventName: binding.arg || 'click', // 支持 v-clickoutside:customEvent
    }
    document.addEventListener(el[clickoutsideContext].eventName, handler)
  },
  updated(el, binding) {
    el[clickoutsideContext].handler = (event) => {
      if (!el.contains(event.target) && el !== event.target) {
        binding.value(event)
      }
    }
  },
  unmounted(el) {
    document.removeEventListener(
      el[clickoutsideContext].eventName,
      el[clickoutsideContext].handler
    )
    delete el[clickoutsideContext]
  },
}
